package com.example.xyxwebbackend001.security;

import cn.dev33.satoken.exception.NotLoginException;
import com.example.xyxwebbackend001.common.CommonResult;
import com.example.xyxwebbackend001.model.vo.ExceptionWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.converter.HttpMessageNotReadableException;

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult<Object> handleJsonParseException(HttpMessageNotReadableException ex) {
        return CommonResult.fail(400, "请求体JSON格式错误");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<ExceptionWrapper> handleException(Exception e, HttpServletRequest request) {
        ExceptionWrapper wrapper;
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;

        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            wrapper = ExceptionWrapper.getNotLogin().setMessage(ee.getMessage());
            status = HttpStatus.UNAUTHORIZED;
        } else {
            wrapper = new ExceptionWrapper()
                    .setCode("500")
                    .setMessage("服务器内部错误: " + e.getMessage());
        }

        return new ResponseEntity<>(wrapper, status);
    }
}
